package com.hsxxherp.simplify.config;

import com.hsxxherp.simplify.ip2region.Ip2Region;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * Ip2Region 自动装配
 *
 * @author Mark·虎克 (2486970363@qq.com)
 */
@Configuration
@EnableConfigurationProperties(Ip2RegionProperties.class)
public class Ip2RegionAutoConfiguration {


    private final Ip2RegionProperties properties;

    public Ip2RegionAutoConfiguration(Ip2RegionProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public Searcher searcher() throws IOException {
        ClassPathResource resource = new ClassPathResource(properties.getDbPath());
        return Searcher.newWithBuffer(resource.getInputStream().readAllBytes());
    }

    @Bean
    @ConditionalOnMissingBean
    public Ip2Region ip2RegionService(Searcher searcher) {
        return new Ip2Region(searcher);
    }
}